package com.bailian.app.util;

import com.bailian.common.core.domain.AjaxResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户上下文工具类
 * 用于统一获取当前用户ID和相关信息
 * 
 * @author bailian
 */
public class UserContextUtil {

    /**
     * 从当前请求中获取用户ID
     * 
     * @return 用户ID
     * @throws RuntimeException 如果用户ID不存在或无效
     */
    public static Long getCurrentUserId() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new RuntimeException("无法获取请求上下文");
        }
        
        HttpServletRequest request = attributes.getRequest();
        Object userIdObj = request.getAttribute("userId");
        
        if (userIdObj == null) {
            throw new RuntimeException("用户未登录或token无效");
        }
        
        if (userIdObj instanceof Long) {
            return (Long) userIdObj;
        } else if (userIdObj instanceof String) {
            try {
                return Long.valueOf((String) userIdObj);
            } catch (NumberFormatException e) {
                throw new RuntimeException("用户ID格式无效");
            }
        } else {
            throw new RuntimeException("用户ID类型无效");
        }
    }

    /**
     * 从当前请求中获取用户ID，如果失败则返回null
     * 
     * @return 用户ID，如果获取失败则返回null
     */
    public static Long getCurrentUserIdOrNull() {
        try {
            return getCurrentUserId();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 检查当前用户是否已登录
     * 
     * @return true表示已登录，false表示未登录
     */
    public static boolean isUserLoggedIn() {
        return getCurrentUserIdOrNull() != null;
    }

    /**
     * 获取当前请求对象
     * 
     * @return HttpServletRequest对象
     */
    public static HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new RuntimeException("无法获取请求上下文");
        }
        return attributes.getRequest();
    }
} 